using Microsoft.AspNetCore.Mvc;
using Lzfy_His_Service.Services;
using Lzfy_His_Service.Repositories;
using Oracle.ManagedDataAccess.Client;

namespace Lzfy_His_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ConnectionOptimizationController : ControllerBase
    {
        private readonly ConnectionLeakDetector _leakDetector;
        private readonly OracleConnectionPoolOptimizer _optimizer;
        private readonly IOracleConnectionManager _connectionManager;
        private readonly IRefundTaskMasterRepository _refundTaskMasterRepository;
        private readonly ILogger<ConnectionOptimizationController> _logger;

        public ConnectionOptimizationController(
            ConnectionLeakDetector leakDetector,
            OracleConnectionPoolOptimizer optimizer,
            IOracleConnectionManager connectionManager,
            IRefundTaskMasterRepository refundTaskMasterRepository,
            ILogger<ConnectionOptimizationController> logger)
        {
            _leakDetector = leakDetector;
            _optimizer = optimizer;
            _connectionManager = connectionManager;
            _refundTaskMasterRepository = refundTaskMasterRepository;
            _logger = logger;
        }

        [HttpGet("pool-stats")]
        public async Task<IActionResult> GetPoolStats()
        {
            try
            {
                var stats = await _optimizer.GetPoolStatsAsync();
                var leaks = _leakDetector.GetConnectionStats();
                
                return Ok(new
                {
                    PoolStats = stats,
                    LeakDetection = leaks,
                    Timestamp = DateTime.UtcNow
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取连接池统计失败");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        [HttpPost("optimize-pool")]
        public async Task<IActionResult> OptimizePool([FromBody] PoolOptimizationRequest request)
        {
            try
            {
                var result = await _optimizer.OptimizeConnectionStringAsync(
                    request.MaxPoolSize ?? 100,
                    request.ConnectionTimeout ?? 60,
                    request.MinPoolSize ?? 10);

                return Ok(new
                {
                    Optimized = result,
                    Message = "连接池已优化",
                    NewSettings = new
                    {
                        MaxPoolSize = request.MaxPoolSize ?? 100,
                        ConnectionTimeout = request.ConnectionTimeout ?? 60,
                        MinPoolSize = request.MinPoolSize ?? 10
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "优化连接池失败");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        [HttpGet("test-connection-leak-detection")]
        public async Task<IActionResult> TestConnectionLeak()
        {
            try
            {
                // 故意创建一些连接来测试泄漏检测
                var tasks = new List<Task>();
                for (int i = 0; i < 5; i++)
                {
                    tasks.Add(Task.Run(async () =>
                    {
                        using var connection = new OracleConnection(
                            "User Id=his;Password=his;Data Source=hisdb;Max Pool Size=5;Min Pool Size=1");
                        await connection.OpenAsync();
                        await Task.Delay(100);
                    }));
                }

                await Task.WhenAll(tasks);
                await Task.Delay(1000); // 等待连接回收

                var stats = _leakDetector.GetConnectionStats();
                return Ok(new
                {
                    Message = "连接泄漏测试完成",
                    Stats = stats,
                    Recommendations = _leakDetector.GetCleanupRecommendations()
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试连接泄漏失败");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        [HttpGet("test-optimized-query")]
        public async Task<IActionResult> TestOptimizedQuery()
        {
            try
            {
                var result = await _refundTaskMasterRepository.GetByIdAsync(1);
                return Ok(new
                {
                    Data = result,
                    Message = "优化后的查询测试完成",
                    OptimizationApplied = new[]
                    {
                        "连接泄漏检测",
                        "性能监控",
                        "连接池状态监控",
                        "详细的错误处理"
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "优化查询测试失败");
                return StatusCode(500, new { error = ex.Message });
            }
        }

        [HttpPost("clear-pools")]
        public IActionResult ClearAllPools()
        {
            try
            {
                OracleConnection.ClearAllPools();
                _logger.LogInformation("所有Oracle连接池已清理");
                return Ok(new { Message = "所有连接池已清理" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理连接池失败");
                return StatusCode(500, new { error = ex.Message });
            }
        }
    }

    public class PoolOptimizationRequest
    {
        public int? MaxPoolSize { get; set; }
        public int? ConnectionTimeout { get; set; }
        public int? MinPoolSize { get; set; }
    }
}